#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include "ds1338c.h"
#include "encode.h"

#define BCD_TO_DEC(val) (((val)&15) + ((val)>>4)*10)
#define DEC_TO_BCD(val)	((((val)/10)<<4) + (val)%10)

#define DEC_BCD(value)	((((value)/10)*16) + ((value)%10))


void help()
{
	printf("\tparameter : [-y] year [-m] month [-d] day [-t] hour [-u] minute [-s] second [-h] help\n");
	//printf("\tformat :  [year] [month]  [day]  [hour]  [minute]  [second]  !\n");
}

int main(int argc, char **argv)
{
	int dev;
	ds_rtc_time time;
	int ch;

	if (argc < 2) {
		help();
		exit(1);
	}

#if 0
	int year, month, day, hour, minute, second;

	printf("input: year month day hour minute second\n");
	scanf("%x %x %x %x %x %x", &year, &month, &day, &hour, &minute, &second);
	time.year = (unsigned char)year;
	time.month = (unsigned char)month;
	time.day = (unsigned char)day;
	time.hour = (unsigned char)hour;
	time.minute = (unsigned char)minute;
	time.second = (unsigned char)second;
#endif
	
	while ((ch = getopt(argc, argv, "y:m:d:t:u:s:h")) != -1) {
		switch(ch) {
			case 'y':
				time.year = (atol(optarg));
				break;
			case 'm':
				time.month = (atoi(optarg));
				break;
			case 'd':
				time.day = (atoi(optarg));
				break;
			case 't':
				time.hour = (atoi(optarg));
				break;
			case 'u':
				time.minute = (atoi(optarg));
				break;
			case 's':
				time.second = (atoi(optarg));
				break;
			case 'h':
				help();
				exit(1);
				break;
			case '?':
				printf("Unknown option : %c.\n", (char)optopt);
			default:
				break;
		}
	}
		

	/* set time */
	#if 0
	time.year = (unsigned char)0x11;
	time.month = (unsigned char)0x12;
	time.day = (unsigned char)0x31;
	time.hour = (unsigned char)0x14;
	time.minute = (unsigned char)0x52;
	time.second = (unsigned char)0x00;	

	time.year = DEC_TO_BCD((unsigned char)11);
	time.month = DEC_TO_BCD((unsigned char)12);
	time.day = DEC_TO_BCD((unsigned char)31);
	time.hour = DEC_TO_BCD((unsigned char)14);
	time.minute = DEC_TO_BCD((unsigned char)52);
	time.second = DEC_TO_BCD((unsigned char)01);
	#endif

	#ifdef HI3511
	dev = open("/dev/misc/ds1338", O_RDONLY);
	#else
	dev = open("/dev/ds1338", O_RDONLY);
	#endif
	if (dev <= 0) {
		printf("ds1338 device open fail\n");
		exit(0);
	}

	// printf("\t[application][%s:%d]\t[0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x]\n",__FUNCTION__,
	//		__LINE__, time.year, time.month, time.day, time.hour, time.minute, time.second);

	printf("\t[application][%s:%d]\t[%d %d %d %d %d %d]\n",__FUNCTION__,
			__LINE__, time.year, time.month, time.day, time.hour, time.minute, time.second);

	ioctl(dev, DS1338_RTC_WRITE_TIME,&time);	

	close(dev);

	return 0;
}
